<?php

namespace Upfor\UpforPHP;

use InvalidArgumentException;

class Cache {

    /**
     * Default driver
     *
     * @var string
     */
    protected static $defaultDriver = 'File';

    protected static $cacheDrivers = [];

    /**
     * Set default cache driver
     *
     * @param string $driver
     */
    public static function setDefaultDriver($driver) {
        self::driver($driver);
        self::$defaultDriver = $driver;
    }

    /**
     * Get current default driver name
     *
     * @return string
     */
    public static function getDefaultDriverName() {
        return self::$defaultDriver;
    }

    /**
     * Get default driver object
     *
     * @return object
     */
    public static function getDefaultDriver() {
        return self::driver(self::$defaultDriver);
    }

    /**
     * Get or initial configuration for a cache driver
     *
     * @param  string $driver
     * @param  array  $config
     * @return mixed
     */
    public static function driver($driver = null, $config = null) {
        if (!$driver) {
            $driver = self::$defaultDriver;
        }

        if (isset(self::$cacheDrivers[$driver])) {
            return self::$cacheDrivers[$driver];
        }

        if (!$config) {
            $config = config('cache')[$driver];
            if (!$config) {
                throw new InvalidArgumentException("Cache store [{$driver}] is not defined");
            }
        }

        $driverClass = false !== strpos($driver, '\\') ? $driver : '\\Upfor\\UpforPHP\\Cache\\' . ucfirst($driver);
        if (!class_exists($driverClass)) {
            throw new InvalidArgumentException("Driver [{$driver}] is not supported");
        }

        return self::$cacheDrivers[$driver] = new $driverClass($config);
    }

}
